/*
 * @Author: 哈尔滨大拐 3181845089@qq.com
 * @Date: 2022-07-17 14:35:26
 * @LastEditors: 哈尔滨大拐 3181845089@qq.com
 * @LastEditTime: 2022-07-22 20:13:52
 * @FilePath: \mygit\实验\购物车\imgs\script1.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
//定义商品数据
const productData = [
    {
        id: 1001,
        imgUrl: "./imgs/apple.png",
        title: "苹果",
        titleEn: "Apple",
        price: 2.99,
    },
    {
        id: 1002,
        imgUrl: "./imgs/beer.png",
        title: "啤酒",
        titleEn: "Bee",
        price: 14.99,
    },
    {
        id: 1003,
        imgUrl: "./imgs/milk.png",
        title: "牛奶",
        titleEn: "Milk",
        price: 4.99,
    },
    {
        id: 1004,
        imgUrl: "./imgs/doughnut.png",
        title: "甜甜圈",
        titleEn: "Doughnut",
        price: 19.99,
    },
    {
        id: 1005,
        imgUrl: "./imgs/bread.png",
        title: "面包",
        titleEn: "Bread",
        price: 3.99,
    },
    {
        id: 1006,
        imgUrl: "./imgs/aubergine.png",
        title: "茄子",
        titleEn: "Aubergine",
        price: 3.49,
    },
    {
        id: 1007,
        imgUrl: "./imgs/lettuce.png",
        title: "生菜",
        titleEn: "Lettuce",
        price: 2.99,
    },
    {
        id: 1008,
        imgUrl: "./imgs/flour.png",
        title: "谷物",
        titleEn: "Flour",
        price: 17.99,
    },
]


let productList = document.querySelector('#product-list')
let cartList = document.querySelector('#cart-list')
let totalPrice = document.querySelector(".total .price");

// 生成商品列表
productData.forEach((product) => {
    // productList.insertAdjacentHTML('beforeend', `
    // <li>
    //     <img src="${product.imgUrl}" alt="">
    //     <h4>${product.title}</h4>
    //     <h5>${product.titleEn}</h5>
    //     <h6>¥${product.price}</h6>
    //     <button prod-id='${product.id}'>加入购物车</button>
    // </li>
    // `
    // )

    let li = document.createElement("li")
    li.innerHTML = `
        <img src="${product.imgUrl}" alt="">
        <h4>${product.title}</h4>
        <h5>${product.titleEn}</h5>
        <h6>¥${product.price}</h6>
        <button prod-id='${product.id}'>加入购物车</button>
    `;
    li.prod = product;
    productList.appendChild(li)

});

// 从cookie中取出事件
let cookieData = getCookie("cartData")
const cartData = cookieData ? JSON.parse(cookieData) : []

// 生成购物车列表
cartData.forEach((product) => {
    insertLiToCart(product)
    // calcTotalPrice()
})

calcTotalPrice();


// 利用事件委托将加入购物车的点击事件绑定给product-list
productList.addEventListener('click', (e) => {
    let target = e.target
    if (target.tagName === "BUTTON") {
        // let productId = target.getAttribute("prod-id")

        // let product = productDate.find(element => {
        //     return element.id == productId;
        // })

        // console.log(product);

        let product = target.parentNode.prod
        product.quantity = product.quantity || 1;

        let productFromCart = cartData.find((element) => {
            return element.id == product.id
        })

        if (productFromCart) {
            // 改变cartList中对应的quantity输入框的值
            productFromCart.quantity++
            let quantityInput = productFromCart.dom.querySelector('.quantity-input')
            quantityInput.value = productFromCart.quantity
        } else {
            insertLiToCart(product);
            cartData.push(product);

            // 存入cookie
            setCookie('cartData', JSON.stringify(cartData))
            // deleteCookie('cartData', JSON.stringify(cartData))
            // console.log(getCookie('cartData'));

        }

    }
    calcTotalPrice()
}, false)


// 向cartList中插入li
function insertLiToCart(product) {
    let li = document.createElement("li");
    li.innerHTML = `
    <div class="item">
        <img src="${product.imgUrl}" alt="">
        <p>${product.title}</p>
    </div>
    <div class="price">
        <p>¥${product.price}</p>
    </div>
    <div class="quantity">
        <input type="number" id="${product.id}" class="quantity-input" value="${product.quantity}">
    </div>
    <div class="delete">
        <button class="btn-delete" data-id="${product.id}">X</button>
    </div>
  `;
    cartList.appendChild(li);
    product.dom = li;
}


// quantity输入框的input事件
cartList.addEventListener('input', (e) => {
    let target = e.target
    if (target.className == "quantity-input") {
        cartData.map((product) => {
            if (product.id == target.id) {
                product.quantity = target.value;
            }
        });

        setCookie("cartData", JSON.stringify(cartData))
        calcTotalPrice()
    }
}, false)


// 总价格
function calcTotalPrice() {
    let result = 0
    cartData.forEach((product) => {
        result += product.price * product.quantity
    })
    totalPrice.innerHTML = '$' + result
}

//删除
cartList.addEventListener('click', function (e) {

    const target = e.target
    if (target.className == 'btn-delete') {
        if (confirm("确定删除吗？")) {
            let index = cartData.findIndex((product) => {
                return product.id == target.dataset.id
            })
            cartData.splice(index, 1)
            target.parentNode.parentNode.remove()
            setCookie("cartData", JSON.stringify(cartData));
            calcTotalPrice();
        }

        // let i = deleteCookie('target', target)
        // console.log(i);
    }

})